package org.example.mutithread.future;

import cn.hutool.core.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangjg
 * @desc f
 * @date 2023/03/30 09:00
 **/
public class F5 {

    private static final Logger log = LoggerFactory.getLogger(F5.class);

    public static void main(String[] args) {
        F5 f5 = new F5();
        log.info("-----------start");
        CompletableFuture<String> future = f5.toFuture(new ISender() {
            @Override
            public void send(String str) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("xxxxxxx {}", str);
            }
        });

        future.exceptionally( e -> {
            log.error(e.getMessage(),e);
            return "error";
        }).thenAccept( s -> {
            log.info("str={}",s);
        });
    }

    public CompletableFuture<String> toFuture(ISender iSender){
        CompletableFuture<String> future = new CompletableFuture<>();
        try {
            iSender.send("xxx");
            if( DateUtil.current() % 2 == 1) {
                throw new RuntimeException("f1 Exception");
            }
            future.complete("success");
        }catch (Exception e){
            future.completeExceptionally(e);
        }
        return future;
    }

}
